package com.emm.yixun.customer.service.impl.app.manage;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.emm.yixun.basic.service.*;
import com.emm.yixun.common.app.AddContactWayResDto;
import com.emm.yixun.common.app.AddCustomerIntentionReqDto;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.model.enums.*;
import com.emm.yixun.customer.service.CustomerLogServiceFacade;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.mapper.SalesGroupMapper;
import com.emm.yixun.common.app.AddCustomerReqDto;
import com.emm.yixun.common.app.GetContactWayResDto;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.app.servletentity.FamilyMemberListReq;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.User;

@Service("addCustomerManage")
public class AddCustomerManage {

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private BusinessRelationService businessRelationService;
	
	@Autowired
	private FamilyMemberService familyMemberService;
	
	@Autowired
	private SalesGroupMapper salesGroupMapper;
	
	@Autowired
	private BaseCodeValueService baseCodeValueService;
	@Autowired
	private CustomerLogService customerLogService;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	
	/**
	 * 插入客户基本信息
	 * @param reqDto
	 * @return
	 */
	public CustomerDto addCustomer(AddCustomerReqDto reqDto) {
		CustomerDto customerDto = new CustomerDto();
		BeanUtils.copyProperties(reqDto, customerDto);
		try{
			//当首次接触方式为不为“来电”时，清空“来电”字段，转存“来访”字段
			BaseCodeValue bvc = getBaseCodeValue(customerDto.getProjectId(), "来电");
			if(!reqDto.getFtContactWay().equals(bvc.getId().toString())) {
				customerDto.setFtContactWay(reqDto.getFtContactWay());
				customerDto.setFtContactTime(reqDto.getFtContactTime());
				customerDto.setFtContactContent(reqDto.getFtContactContent());

				if(String.valueOf(customerDto.getMerchantId()).equals(MerchantEnum.GREEN_TOWN.getNo())
				|| String.valueOf(customerDto.getMerchantId()).equals(MerchantEnum.GREEN_TOWN_TEST.getNo())){
					customerDto.setFtContactWay(null);
					customerDto.setFtContactTime(null);
					customerDto.setFtContactContent(null);
					customerDto.setFtContactWay1(reqDto.getFtContactWay());
					customerDto.setFtContactTime1(reqDto.getFtContactTime());
					customerDto.setFtContactContent1(reqDto.getFtContactContent());
				}
				//客户状态为来访
				customerDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
			} else {
				//客户状态为来电
				customerDto.setCustomerStatus(CustomerStatusEnum.CALL.getNo());
			}
			//当首次接触方式为“电转访”时，则修改“电转访”为“来访”
			if(StringUtils.isNotBlank(reqDto.getFtContactWay1())) {
				String codeName = getCodeName(reqDto.getFtContactWay1());
				if("电转访".equals(codeName)) {
					bvc = getBaseCodeValue(customerDto.getProjectId(), "来访");
					customerDto.setFtContactWay1(bvc.getId().toString());
				}
			}

			customerDto.setMobile2(reqDto.getMobile2());
			customerDto.setIsDistribution(IsDistributionEnum.UNDISTRIBUTION.getNo());
			customerDto.setPublicSigns(PublicSignsEnum.PUBLIC.getNo());
			customerDto.setDistributionNum(0L);
			customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			customerDto.setProcessStatus(ProcessStatusEnum.ADDBAK.getNo());
			customerDto.setLastFollowTime(new Date());//新增客户时：默认最后跟进时间为当前系统时间
			if(reqDto.getQqNum() != null){
				customerDto.setQqNumber(reqDto.getQqNum());
			}
			if(reqDto.getIndustry() != null){
				customerDto.setCongshihangye(reqDto.getIndustry());
			}
			if(reqDto.getNatureCompany() != null){
				customerDto.setCompanyXingzhi(reqDto.getNatureCompany());
			}
			if(reqDto.getAnnualTurnoverCompany() != null){
				customerDto.setCompanyYingye(reqDto.getAnnualTurnoverCompany());
			}
			if(reqDto.getFamilyStructure() != null){
				customerDto.setFamilyJie(reqDto.getFamilyStructure());
			}
			if(reqDto.getIsEmployees() != null){
				customerDto.setIsYuangong(reqDto.getIsEmployees());
			}
			if(reqDto.getIsOwnerCompany() != null){
				customerDto.setIsYezhu(reqDto.getIsOwnerCompany());
			}
			if(reqDto.getIsLiveElderly() != null){
				customerDto.setIsLaoren(reqDto.getIsLiveElderly());
			}
			if(reqDto.getIsChildren() != null){
				customerDto.setIsZinv(reqDto.getIsChildren());
			}
			if(reqDto.getIntentionPropertyType() != null){
				customerDto.setYixiangwuyeType(reqDto.getIntentionPropertyType());
			}
			customerDto.setXuqiuhuxingType(reqDto.getSpecifications());
			if(reqDto.getDailyInformation() != null && !"".equals(reqDto.getDailyInformation())){
				customerDto.setRichangxinxi(reqDto.getDailyInformation());
			}
			if(reqDto.getBuyParking() != null){
				customerDto.setBuyCar(reqDto.getBuyParking());
			}
			Long salesGroupId = salesGroupMapper.selectGroupId(reqDto.getMerchantId(), reqDto.getProjectCode(), Long.valueOf(reqDto.getUserId()));
			if(salesGroupId != null){
				customerDto.setSalesGroupId(salesGroupId);
			}
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			customerDto.setUserCode(user.getUserCode());
			customerDto.setAccessCode(reqDto.getProjectCode());
			customerDto.setCreateUserId(Long.parseLong(reqDto.getUserId()));
			customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			//客户初始状态
			if(reqDto.getCustomerStatus() != null){
				customerDto.setCustomerStatusBk(reqDto.getCustomerStatus());
			}
			customerDto = customerService.create(customerDto);

			customerServiceFacade.changeCustomerPerfect(customerDto.getId());

			//比较字段变更差异
			compareCustomer(customerDto, customerDto, "INSERT", reqDto.getUserId());

		}catch(Exception e){
			e.printStackTrace();
			customerDto = null;
		}
		return customerDto;
	}
	
	/**
	 * 查询当前项目的基础参数
	 */
	private BaseCodeValue getBaseCodeValue(Long projectId, String codeName) {
		BaseCodeValueDto entity = new BaseCodeValueDto();
		entity.setProjectId(projectId);
		entity.setCodeName(codeName);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		BaseCodeValue bcv = baseCodeValueService.selectByDto(entity);
		return bcv;
	}

	/**
	 * 插入客户基本信息（绿城 判断客户意向等级)
	 * @param reqDto
	 * @return
	 */
	public CustomerDto addCustomer(AddCustomerIntentionReqDto reqDto) {
		CustomerDto customerDto = new CustomerDto();
		BeanUtils.copyProperties(reqDto, customerDto);
		try{
			//当首次接触方式为不为“来电”时，清空“来电”字段，转存“来访”字段
			BaseCodeValue bvc = getBaseCodeValue(customerDto.getProjectId(), "来电");
			if(!reqDto.getFtContactWay().equals(bvc.getId().toString())) {
				customerDto.setFtContactWay(null);
				customerDto.setFtContactTime(null);
				customerDto.setFtContactContent(null);
				customerDto.setFtContactWay1(reqDto.getFtContactWay());
				customerDto.setFtContactTime1(reqDto.getFtContactTime());
				customerDto.setFtContactContent1(reqDto.getFtContactContent());
				//客户状态为来访
				customerDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
			} else {
				//客户状态为来电
				customerDto.setCustomerStatus(CustomerStatusEnum.CALL.getNo());
			}
			//当首次接触方式为“电转访”时，则修改“电转访”为“来访”
			if(StringUtils.isNotBlank(customerDto.getFtContactWay1())) {
				String codeName = getCodeName(customerDto.getFtContactWay1());
				if("电转访".equals(codeName)) {
					bvc = getBaseCodeValue(customerDto.getProjectId(), "来访");
					customerDto.setFtContactWay1(bvc.getId().toString());
				}
			}
			customerDto.setIsDistribution(IsDistributionEnum.UNDISTRIBUTION.getNo());
			customerDto.setPublicSigns(PublicSignsEnum.PUBLIC.getNo());
			customerDto.setDistributionNum(0L);
			customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			customerDto.setProcessStatus(ProcessStatusEnum.ADDBAK.getNo());
			customerDto.setLastFollowTime(new Date());//新增客户时：默认最后跟进时间为当前系统时间
			if(reqDto.getQqNum() != null){
				customerDto.setQqNumber(reqDto.getQqNum());
			}
			if(reqDto.getIndustry() != null){
				customerDto.setCongshihangye(reqDto.getIndustry());
			}
			if(reqDto.getNatureCompany() != null){
				customerDto.setCompanyXingzhi(reqDto.getNatureCompany());
			}
			if(reqDto.getAnnualTurnoverCompany() != null){
				customerDto.setCompanyYingye(reqDto.getAnnualTurnoverCompany());
			}
			if(reqDto.getFamilyStructure() != null){
				customerDto.setFamilyJie(reqDto.getFamilyStructure());
			}
			if(reqDto.getIsEmployees() != null){
				customerDto.setIsYuangong(reqDto.getIsEmployees());
			}
			if(reqDto.getIsOwnerCompany() != null){
				customerDto.setIsYezhu(reqDto.getIsOwnerCompany());
			}
			if(reqDto.getIsLiveElderly() != null){
				customerDto.setIsLaoren(reqDto.getIsLiveElderly());
			}
			if(reqDto.getIsChildren() != null){
				customerDto.setIsZinv(reqDto.getIsChildren());
			}
			if(reqDto.getIntentionPropertyType() != null){
				customerDto.setYixiangwuyeType(reqDto.getIntentionPropertyType());
			}
			customerDto.setXuqiuhuxingType(reqDto.getSpecifications());
			if(reqDto.getDailyInformation() != null && !"".equals(reqDto.getDailyInformation())){
				customerDto.setRichangxinxi(reqDto.getDailyInformation());
			}
			if(reqDto.getBuyParking() != null){
				customerDto.setBuyCar(reqDto.getBuyParking());
			}
			Long salesGroupId = salesGroupMapper.selectGroupId(reqDto.getMerchantId(), reqDto.getProjectCode(), Long.valueOf(reqDto.getUserId()));
			if(salesGroupId != null){
				customerDto.setSalesGroupId(salesGroupId);
			}
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			customerDto.setUserCode(user.getUserCode());
			customerDto.setAccessCode(reqDto.getProjectCode());
			customerDto.setCreateUserId(Long.parseLong(reqDto.getUserId()));
			customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			//客户初始状态
			if(reqDto.getCustomerStatus() != null){
				customerDto.setCustomerStatusBk(reqDto.getCustomerStatus());
			}
			customerDto = customerService.create(customerDto);
		}catch(Exception e){
			e.printStackTrace();
			customerDto = null;
		}
		return customerDto;
	}


	/**
	 * 插入客户基本信息
	 * @param customerDto
	 * @return
	 */
	public CustomerDto allAddCustomer(CustomerDto customerDto) {
		try{
			customerDto.setIsDistribution(IsDistributionEnum.UNDISTRIBUTION.getNo());
			customerDto.setPublicSigns(PublicSignsEnum.PUBLIC.getNo());
			customerDto.setDistributionNum(0L);
			customerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			customerDto.setProcessStatus(ProcessStatusEnum.ADDBAK.getNo());
			customerDto.setLastFollowTime(new Date());//新增客户时：默认最后跟进时间为当前系统时间
			Long salesGroupId = salesGroupMapper.selectGroupId(customerDto.getMerchantId(), customerDto.getProjectCode(), Long.valueOf(customerDto.getUserId()));
			if(salesGroupId != null){
				customerDto.setSalesGroupId(salesGroupId);
			}
			customerDto = customerService.create(customerDto);
		}catch(Exception e){
			e.printStackTrace();
			customerDto = null;
		}
		return customerDto;
	}
	
	public CustomerDto updateCustomer(AddCustomerReqDto reqDto) {
		CustomerDto customerDto = new CustomerDto();
		BeanUtils.copyProperties(reqDto, customerDto);
		//判断客户状态是来访还是来电
		BaseCodeValue bvc = getBaseCodeValue(customerDto.getProjectId(), "来电");
		if(!reqDto.getFtContactWay().equals(bvc.getId().toString())) {
			//客户状态为来电
			customerDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
		} else {
			//客户状态为来访
			customerDto.setCustomerStatus(CustomerStatusEnum.CALL.getNo());
		}
		customerDto.setQqNumber(reqDto.getQqNum());
		customerDto.setCongshihangye(reqDto.getIndustry());
		customerDto.setCompanyXingzhi(reqDto.getNatureCompany());
		customerDto.setCompanyYingye(reqDto.getAnnualTurnoverCompany());
		customerDto.setFamilyJie(reqDto.getFamilyStructure());
		customerDto.setIsYuangong(reqDto.getIsEmployees());
		customerDto.setIsYezhu(reqDto.getIsOwnerCompany());
		customerDto.setIsLaoren(reqDto.getIsLiveElderly());
		customerDto.setIsZinv(reqDto.getIsChildren());
		customerDto.setYixiangwuyeType(reqDto.getIntentionPropertyType());
		customerDto.setXuqiuhuxingType(reqDto.getSpecifications());
		customerDto.setRichangxinxi(reqDto.getDailyInformation());
		customerDto.setBuyCar(reqDto.getBuyParking());
		customerDto.setIntentionLevelRemark(reqDto.getIntentionLevelRemark());
		try{
			//获取变更前记录
			Customer original = customerService.selectById(customerDto.getId());
			CustomerDto originalDto = new CustomerDto();
			if(null != original){
				BeanUtils.copyProperties(original, originalDto);
			}
			//编辑不改变当前经纪人
			//User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			//customerDto.setUserCode(user.getUserCode());
			customerDto.setAccessCode(reqDto.getProjectCode());
			customerDto.setUpdateUserId(Long.parseLong(reqDto.getUserId()));
			/**
			 * 添加判断 A级的必填项填完修改完善信息状态
			 */
			if("2".equals(customerDto.getIntentionLevel()) && isIntentionIntact(customerDto)) {
				customerDto.setIsIntentionIntact("1");
			}
			customerDto = customerService.update(customerDto);
			//比较字段变更差异
			compareCustomer(originalDto, customerDto, "UPDATE", reqDto.getUserId());

			Customer customer = customerService.selectById(customerDto.getId());
			if(null!=customer){
				BeanUtils.copyProperties(customer, customerDto);
			}
		}catch(Exception e){
			e.printStackTrace();
			customerDto = null;
		}
		return customerDto;
	}

	private boolean isIntentionIntact(CustomerDto customer) {
		if(customer == null) {
			return false;
		}
		//信息是否已填完标识(已填完   = true)
		boolean flag = true;
		//客户姓名
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getCustomerName())) {
			flag = false;
		}
		//性别
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getCustomerSex())) {
			flag = false;
		}
		//联系电话
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getCustomerPhone())) {
			flag = false;
		}
		//意向等级
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getIntentionLevel())) {
			flag = false;
		}
		//获知途径
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getInformedWay())) {
			flag = false;
		}
		//首次接触
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getFtContactWay())
				&& customer.getFtContactTime() == null
				&& org.apache.commons.lang.StringUtils.isBlank(customer.getFtContactContent())) {
			//来电
			flag = false;
		} else if(org.apache.commons.lang.StringUtils.isBlank(customer.getFtContactWay())
				&& customer.getFtContactTime() == null
				&& org.apache.commons.lang.StringUtils.isBlank(customer.getFtContactContent())) {
			//来访、电转访
			flag = false;
		}
		//置业动机
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getRqTheirMotives())) {
			flag = false;
		}
		//关注重点
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getRqFocusId())) {
			flag = false;
		}
		//需求面积
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getRqDemandArea())) {
			flag = false;
		}
		//付款方式
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getRqPaymentMethod())) {
			flag = false;
		}
		//生活服务
		if(org.apache.commons.lang.StringUtils.isBlank(customer.getRqPaymentMethod())) {
			flag = false;
		}
		//居住区
		if(customer.getPeResidenceProvinceId() == null
				|| customer.getPeResidenceCityId() == null
				|| customer.getPeResidenceAreaId() == null) {
			flag = false;
		}
		//工作区
		if(customer.getPeWorkaroundProvinceId() == null
				|| customer.getPeWorkaroundCityId() == null
				|| customer.getPeWorkaroundAreaId() == null) {
			flag = false;
		}
		return flag;
	}
	
	/**
	 * 新增客户关注户型
	 * @param houseTypeList 关注户型列表
	 * @return 
	 */
	public CommonResDTO addCusHouseTypeFocus(CustomerDto customerDto, List<String> houseTypeList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			for (String houseType: houseTypeList) {
				JSONObject object = JSONObject.parseObject(houseType);
				long houseTypeId = object.getLongValue("houseTypeId");
				BusinessRelationDto brDto = new BusinessRelationDto();
				brDto.setProjectId(customerDto.getProjectId());
				brDto.setProjectCode(customerDto.getProjectCode());
				brDto.setSingleId(customerDto.getId());
				brDto.setRelationType(RelationTypeEnum.HOUSE_TYPE.getNo());
				brDto.setMoreId(houseTypeId);
				brDto.setMerchantId(customerDto.getMerchantId());
				brDto.setUserCode(customerDto.getUserCode());
				brDto.setAccessCode(customerDto.getAccessCode());
				brDto.setCreateUserId(customerDto.getCreateUserId());
				brDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				brDto.setRemark("客户关注户型");
				businessRelationService.create(brDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增客户,关注户型失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增客户关注组团(楼盘)
	 * 
	 * @param customerDto 客户信息
	 * @param premisesList 关注组团(楼盘)列表
	 * @return 
	 */
	public CommonResDTO addCusPremisesFocus(CustomerDto customerDto, List<String> premisesList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			for (String premises: premisesList) {
				JSONObject object = JSONObject.parseObject(premises);
				long premisesId = object.getLongValue("premisesId");
				BusinessRelationDto brDto = new BusinessRelationDto();
				brDto.setProjectId(customerDto.getProjectId());
				brDto.setProjectCode(customerDto.getProjectCode());
				brDto.setSingleId(customerDto.getId());
				brDto.setRelationType(RelationTypeEnum.PREMISES.getNo());
				brDto.setMoreId(premisesId);
				brDto.setMerchantId(customerDto.getMerchantId());
				brDto.setUserCode(customerDto.getUserCode());
				brDto.setAccessCode(customerDto.getAccessCode());
				brDto.setCreateUserId(customerDto.getCreateUserId());
				brDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				brDto.setRemark("客户意向组团");
				businessRelationService.create(brDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增客户,意向组团添加失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增客户关注房号
	 * 
	 * @param customerDto 客户信息
	 * @param roomList 关注房号列表
	 * @return 
	 */
	public CommonResDTO addCusRoomFocus(CustomerDto customerDto, List<String> roomList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			for (String room: roomList) {
				JSONObject object = JSONObject.parseObject(room);
				long roomId = object.getLongValue("roomId");
				BusinessRelationDto brDto = new BusinessRelationDto();
				brDto.setProjectId(customerDto.getProjectId());
				brDto.setProjectCode(customerDto.getProjectCode());
				brDto.setSingleId(customerDto.getId());
				brDto.setRelationType(RelationTypeEnum.ROOM.getNo());
				brDto.setMoreId(roomId);
				brDto.setMerchantId(customerDto.getMerchantId());
				brDto.setUserCode(customerDto.getUserCode());
				brDto.setAccessCode(customerDto.getAccessCode());
				brDto.setCreateUserId(customerDto.getCreateUserId());
				brDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				brDto.setRemark("客户关注房号");
				businessRelationService.create(brDto);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增客户,关注房号添加失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 新增客户家庭成员
	 * 
	 * @param customerDto 客户信息
	 * @param familyMemberList 客户家庭成员列表
	 * @return 
	 */
	public CommonResDTO addCusFamily(CustomerDto customerDto, List<FamilyMemberListReq> familyMemberList){
		CommonResDTO resDto = new CommonResDTO();
		try {
			int index = 0;
			for (FamilyMemberListReq family: familyMemberList) {
				String memberName = family.getMemberName();
				String birthday = family.getBirthday();
				String marryday = family.getMarryday();
				FamilyMemberDto fmDto = new FamilyMemberDto();
				fmDto.setCustomerId(customerDto.getId());
				fmDto.setProjectId(customerDto.getProjectId());
				fmDto.setProjectCode(customerDto.getProjectCode());
				fmDto.setBuyId(customerDto.getId());
				fmDto.setDocumentNumber(family.getDocumentNumber());
				fmDto.setDocumentType(family.getDocumentType());
				fmDto.setMemberName(memberName);
				fmDto.setSex(SexEnum.UNKNOW.getNo());
				fmDto.setMobile(family.getMobile());
				fmDto.setRelationship(family.getRelationship());
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if(StringUtils.isNotBlank(birthday)){
					fmDto.setBirthday(sdf.parse(birthday));
				}else{
					fmDto.setBirthday(null);
				}
				if(marryday != null && !"".equals(marryday)){
					fmDto.setMarryday(sdf.parse(marryday));
				}
				fmDto.setMemberType(MemberTypeEnum.CUSTOMER_ADD.getNo());
				if(index == 0){
					fmDto.setIsDefault("1");
				}else{
					fmDto.setIsDefault("0");
				}
				fmDto.setMerchantId(customerDto.getMerchantId());
				fmDto.setUserCode(customerDto.getUserCode());
				fmDto.setAccessCode(customerDto.getAccessCode());
				fmDto.setCreateUserId(customerDto.getCreateUserId());
				fmDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				fmDto.setRemark("添加客户家庭成员");
				familyMemberService.create(fmDto);
				index++;
			}
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("新增客户,家庭成员添加失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}
	
	/**
	 * 修改首次接触方式
	 * @param reqDto
	 * @return
	 */
	public AddContactWayResDto addContactWay(CustomerDto reqDto) {
		AddContactWayResDto resDto = new AddContactWayResDto();
		try {
			CustomerDto entity = new CustomerDto();
			entity.setId(reqDto.getId());
			entity.setProjectId(reqDto.getProjectId());
			Customer cus = customerService.selectByDto(entity);
			//已存在来访时,禁止修改
			if(StringUtils.isNotBlank(cus.getFtContactWay1())) {
				resDto.setErrorCode("0000");
				resDto.setErrorMsg("已有来访内容，禁止修改!");
				resDto.setResult(ResultEnum.FAILURE.getNo());
			}
			String ftContactWay1 = reqDto.getFtContactWay1();
			if("电转访".equals(reqDto.getFtContactWay1())) {
				BaseCodeValue bvc = getBaseCodeValue(reqDto.getProjectId(), "电转访");
				ftContactWay1 = bvc.getId().toString();
				reqDto.setFtContactWay1(ftContactWay1);
			}
			
			//是否已存在来电的业务逻辑
			if(StringUtils.isNotBlank(cus.getFtContactWay())) {
				//已存在来电时
				//禁止修改首次来电
				reqDto.setFtContactWay(null);
				reqDto.setFtContactTime(null);
				reqDto.setFtContactContent(null);
				//新增来访方式为"来访"时，修改“来访”为“电转访”
				if (StringUtils.isNotBlank(reqDto.getFtContactWay1())) {
					String codeName = getCodeName(ftContactWay1);
					if ("来访".equals(codeName)) {
						reqDto.setFtContactWay1(ftContactWay1);
					}
				}
			} else {
				//不存在来电时
				//新增来访方式为“电转访”时，判断是否有“来电”，如没有，则修改“电转访”为“来访”
				if (StringUtils.isNotBlank(reqDto.getFtContactWay1())) {
					String codeName = getCodeName(ftContactWay1);
					if ("电转访".equals(codeName) 
							&& StringUtils.isBlank(reqDto.getFtContactWay())) {
						BaseCodeValue bvc = getBaseCodeValue(reqDto.getProjectId(), "来访");
						reqDto.setFtContactWay1(bvc.getId().toString());
					}
				}
			}
			//修改客户状态为来访
			reqDto.setCustomerStatus(CustomerStatusEnum.VISIT.getNo());
			customerService.update(reqDto);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto = new AddContactWayResDto();
			resDto.setErrorCode("9999");
			resDto.setErrorMsg("修改首次接触方式失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
	/**
	 * 根据字典ID获取字典名称
	 * @param bcvId
	 * @return
	 */
	private String getCodeName(String bcvId) {
		if(StringUtils.isBlank(bcvId)) {
			return null;
		}
		BaseCodeValue bcv = baseCodeValueService.selectById(Long.parseLong(bcvId));
		if(bcv == null) {
			return null;
		}
		return bcv.getCodeName();
	}
	
	/**
	 * 获取首次接触方式
	 * @param reqDto
	 * @return
	 */
	public GetContactWayResDto getContactWay(CustomerDto reqDto) {
		GetContactWayResDto resDto = new GetContactWayResDto();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Customer customer = customerService.selectByDto(reqDto);
			if (customer == null) {
				resDto.setErrorCode("9999");
				resDto.setErrorMsg("未获取到客户信息");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			resDto.setFtContactWay(customer.getFtContactWay());
			resDto.setFtContactWayName(getCodeName(customer.getFtContactWay()));
			resDto.setFtContactTime(customer.getFtContactTime() == null 
					? null : sdf.format(customer.getFtContactTime()));
			resDto.setFtContactContent(customer.getFtContactContent());
			resDto.setFtContactWay1(customer.getFtContactWay1());
			resDto.setFtContactWayName1(getCodeName(customer.getFtContactWay1()));
			resDto.setFtContactTime1(customer.getFtContactTime1() == null 
					? null : sdf.format(customer.getFtContactTime1()));
			resDto.setFtContactContent1(customer.getFtContactContent1());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			resDto = new GetContactWayResDto();
			resDto.setErrorCode("9999");
			resDto.setErrorMsg("获取首次接触方式失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}

	/**
	 * 比较客户字段差异
	 * @param original
	 * @param current
	 * @return
	 * @throws Exception
	 */
	public void compareCustomer(CustomerDto original, CustomerDto current, String optType, String userId){

		JSONObject jsonObject = new JSONObject();
		try{
			if(!"INSERT".equals(optType)){
				Field[] fields = Customer.class.getDeclaredFields();
				for(Field field: fields){
					if("serialVersionUID".equals(field.getName())){
						continue;
					}
					PropertyDescriptor pd = new PropertyDescriptor(field.getName(), Customer.class);
					Method getMethod = pd.getReadMethod();
					Object originalObj = getMethod.invoke(original);
					Object currentObj = getMethod.invoke(current);
					String originalStr = originalObj == null ? "": originalObj.toString();
					String currentStr = currentObj == null ? "": currentObj.toString();
					if(!originalStr.equals(currentStr) && !"".equals(currentStr)){
						jsonObject.put(field.getName(), originalStr + " --> " + currentStr);
					}
				}
			}
			//插入记录
			CustomerLogDto clDto = new CustomerLogDto();
			clDto.setCustomerId(original.getId());
			clDto.setOriginalRecord(JSONObject.toJSONString(original));
			clDto.setCurrentRecord(JSONObject.toJSONString(current));
			clDto.setChangeField(jsonObject.toJSONString());
			clDto.setOptType(optType);
			clDto.setCreateUserId(Long.valueOf(userId));
			clDto.setUpdateTime(Calendar.getInstance().getTime());
			clDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			customerLogService.create(clDto);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}
